//
//  GTFlutter.swift
//  Runner
//
//  Created by Shper on 2023/5/5.
//

import Foundation
import Flutter
import lib_core

public class GTFlutter: NSObject,UIViewControllerTransitioningDelegate {
    
    // 引擎组
    let engineGroup: FlutterEngineGroup = FlutterEngineGroup(name: "GateIO", project: nil)
    // 记录已经启动的页面
    public internal(set) var pageStartedList: [String] = [] {
        didSet {
            config.onStartedPageListChanged?(pageStartedList)
        }
    }
    
    private var config = GTFlutterInitConfig()
    
    // 单例模式
    public static let shared = GTFlutter()
    
    private override init() {}
    
    deinit {
        pageStartedList.removeAll()
    }
    
    /**
     * Flutter 初始化
     */
    public func setup(_ config: GTFlutterInitConfig) {
        self.config = config
    }
    
    /**
     * 打开 Flutter 页面
     * isControllNavigation  true 对导航栏进行处理，flase 对导航栏不做处理
     */
    public func openPage(viewController: UIViewController?,
                         routerName: String,
                         navigationController: UINavigationController? = nil,
                         routeParams: [String: Any]? = nil,
                         isControllNavigation: Bool? = true,
                         customEngineId: String? = nil,
                         nibName: String? = nil,
                         bundle: Bundle? = nil,
                         isDialog: Bool? = false) {
        if(isDialog==true){
            showDialog(viewController: viewController, routerName: routerName,routeParams: routeParams)
            return
        }
        // 创建 Flutter 页面
        let flutterViewController = createViewController(routerName: routerName,
                                                         routeParams: routeParams,
                                                         isControllNavigation: isControllNavigation,
                                                         nibName: nibName,
                                                         bundle: bundle)
        // 打开 Flutter 页面
        if let nav = viewController?.navigationController {
            nav.pushViewController(flutterViewController, animated: true)
        } else {
            navigationController?.pushViewController(flutterViewController, animated: true)
        }
    }
    
    /**
     * 创建 Flutter 页面，可以用于一级、二级页面
     * isControllNavigation  true 对导航栏进行处理，flase 对导航栏不做处理
     */
    public func createViewController(routerName: String,
                                     routeParams: [String: Any]? = nil,
                                     isControllNavigation: Bool? = true,
                                     nibName: String? = nil,
                                     bundle: Bundle? = nil,
                                     customDarkMode: Bool? = nil) -> GTFlutterViewController {
        // 获取 Flutter 引擎
        let engine = makeFlutterEngine(routerName,
                                       routeParams: routeParams,
                                       customDarkMode: customDarkMode)
        // 创建 Flutter 页面
        let flutterViewController = GTFlutterViewController(initRouterName: routerName,
                                                            engine: engine,
                                                            isControllNavigation: isControllNavigation,
                                                            nibName: nibName,
                                                            bundle: bundle)
        config.onViewControllerCreated?(flutterViewController, routerName, routeParams)
        return flutterViewController
    }
    
    /**
     * 创建或复用 Flutter 引擎
     */
    public func makeFlutterEngine(_ routerName: String,
                                  routeParams: [String: Any]? = nil,
                                  customDarkMode: Bool? = nil) -> FlutterEngine {
        // 创建 options 复用引擎
        let options = FlutterEngineGroupOptions()
        options.initialRoute = routerName
        
        // 传递入口参数 + 扩展参数
        var entrypointArgs = [self.config.toJson(extendDic: [:],
                                                 customDarkMode: customDarkMode)]
        // 路由到对应页面的参数
        if (routeParams != nil && !((routeParams ?? [:]).isEmpty)) {
            let routeParamsDic = ["routeParams": GTFlutterUitls.convertDictionaryToString(routeParams ?? [:])]
            entrypointArgs.append(GTFlutterUitls.convertDictionaryToString(routeParamsDic))
        }
        options.entrypointArgs = entrypointArgs
        
        // 不一定每次都会创建，FlutterEngineGroup 会复用
        let flutterEngine = engineGroup.makeEngine(with: options)
        // 注册 Flutter 插件和通道
        self.config.onPluginRegistrant(flutterEngine, routerName)

        return flutterEngine
    }
    
    
    /**
     * 打开 Flutter 页面
     */
    public func showDialog(viewController: UIViewController?,
                           routerName: String,
                           routeParams: [String: Any]? = nil) {
        // 创建 Flutter 页面
        let flutterViewController = createViewController(routerName: routerName,
                                                         routeParams: routeParams,
                                                         isControllNavigation: false
        )
        flutterViewController.view.backgroundColor = UIColor.clear
        flutterViewController.modalPresentationStyle = .overFullScreen
        viewController?.present(flutterViewController, animated: false)
    }
    
    /**
     * 判断是否 某一个 router 代表的页面是否在启动
     */
    public func isPageStarted(routerName: String) -> Bool {
        return pageStartedList.contains(routerName)
    }

//    /**
//     * 获取 FlutterEngine
//     */
//    public func getRunningFlutterEngine(routerName: String,
//                                customEngineId: String? = nil) -> FlutterEngine? {
//        customEngineId?.let {
//            return FlutterEngineCache.getInstance().get(it)
//        } ?: run {
//            return FlutterEngineCache.getInstance().get(routerName)
//        }
//    }
    
    public func removePageStartedList(routerName: String) {
        if (routerName.isEmpty) {
            return
        }
        pageStartedList = pageStartedList.filter { $0 != routerName }
    }
}
